﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.IO;
using Microsoft.WindowsMobile.PocketOutlook;
using System.Windows.Forms;
using System.Threading;
using Microsoft.WindowsMobile.Telephony;

namespace OCDStudio.SMSPPPServer
{
    class TcpClientWrapper
    {

        private TcpClient client;
        private SocketServer server;

        public TcpClientWrapper(SocketServer serv,TcpClient cl)
        {
            this.client = cl;
            this.server = serv;
        }

        public void ManageTcpClient() {
            NetworkStream str = client.GetStream();
            StreamReader reader = new StreamReader(str);
            try
            {

                while (true)
                {
                    string sms = reader.ReadLine();
                    if (sms == "STOP")
                    {
                        server.StopServer();
                        return;
                    }
                    if (sms.StartsWith("CALL")) StartCall(sms);
                    else ManageSms(sms);
                }
            }
            catch (ThreadAbortException)
            {
                client.Close();
                return;
            }
            catch (NullReferenceException)
            {
                client.Close();
                //server.RemoveMe(this);
                return;
            }
            catch (Exception e)
            {
                client.Close();
                MessageBox.Show(e.Message);
                return;
            }
        }

        private void StartCall(string sms)
        {
            string number = sms.Split('$')[1];
            Phone p = new Phone();
            p.Talk(number);
        }
        private void ManageSms(string sms)
        {
            string dest, text;
            dest = sms.Split('$')[0];
            text = sms.Split('$')[1];
            server.Session.SmsAccount.Send(new SmsMessage(dest, text));
        }

    }
}
